package com.ia.bikerecife;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.opengl.Visibility;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.bikerecife.R;
import com.ia.bikerecife.communication.TaskComunication;
import com.ia.bikerecife.maps.Coordenate;
import com.ia.bikerecife.maps.MapActivity;
import com.ia.bikerecife.speech.ISpeech;
import com.ia.bikerecife.speech.SpeechHandle;

public class MainActivity extends Activity implements LocationListener {

    public static String     mMessage = "";

    private SpeechHandle     mSpeechHandle;
    private Dialog           mDialogConfirmation;
    private ProgressDialog   mDialog;
    private TaskComunication mComunicationTask;

    public Context           mContext;
    public ISpeech           mISpeech;
    public Coordenate        mLocation;

    private LinearLayout     mLayoutBallon;
    private TextView         mTextViewBallon;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ImageView avatar = (ImageView) findViewById(R.id.avatar);
        avatar.setOnClickListener(onAvatarClickListener);

        getGPSCoordenates();
        
        mLayoutBallon = (LinearLayout) findViewById(R.id.layoutBallon);
        mTextViewBallon = (TextView) findViewById(R.id.textViewBallon);
        
        mLayoutBallon.setVisibility(View.INVISIBLE);
        mTextViewBallon.setText("");

         // Novo SDK para tratar voz
         // mISpeech = new ISpeech(this);
         mSpeechHandle = new SpeechHandle(this);
         mContext = this;

        startActivity(new Intent(this, SettingsActivity.class));

      
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        startActivity(new Intent(MainActivity.this, SettingsActivity.class));
        return super.onMenuItemSelected(featureId, item);
    }

    public OnClickListener onAvatarClickListener = new OnClickListener() {

                                                     @Override
                                                     public void onClick(View v) {

                                                         v.setEnabled(false);
                                                          mLayoutBallon.setVisibility(View.INVISIBLE);
                                                         mTextViewBallon.setText("");

                                                         mSpeechHandle.CallSpeechRecognizer();

                                                         v.setEnabled(true);
                                                     }
                                                 };

    private void ProcessServerResponse() {
        Log.v("leac", "FromServer: " + mMessage);

        String[] blocks = mMessage.split(";");

        if (!blocks[0].contains("null")) {
            mTextViewBallon.setText(blocks[0]);
            mLayoutBallon.setVisibility(View.VISIBLE);

            Log.v("leac", "speaking: " + blocks[0]);
            mSpeechHandle.StartSpeechSyntesis(blocks[0]);

            // smISpeech.StartSpeechSyntesis(blocks[0]);
        }

        if (blocks.length > 1 && !(blocks[1].compareTo("null") == 0)) {
            Log.v("leac", "showing maps");
            Coordenate destination = new Coordenate();
            destination.setLatitude(Double.parseDouble(blocks[1]));
            destination.setLongitude(Double.parseDouble(blocks[2]));

            if (mLocation.getLatitude() == 0 && SettingsActivity.mUseUnicapLocation) {
                mLocation = SettingsActivity.mUnicapLocation;
            }

            ShowMaps(mLocation, destination);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        String returnMensage = mSpeechHandle.onActivityResult(requestCode, resultCode, data);
        if (returnMensage.length() > 0) {
            ShowConfirmationDialog(returnMensage);
        }

    }

    private void ShowConfirmationDialog(String message) {
        mDialogConfirmation = new Dialog(MainActivity.this);
        mDialogConfirmation.setContentView(R.layout.dialog_confirmation);
        mDialogConfirmation.setTitle("Você quis dizer:");

        ((EditText) mDialogConfirmation.findViewById(R.id.editTextMessage)).setText(message);
        ((Button) mDialogConfirmation.findViewById(R.id.buttonConfirm)).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                mDialogConfirmation.dismiss();
                String message = ((EditText) mDialogConfirmation.findViewById(R.id.editTextMessage)).getEditableText()
                        .toString();

                if (mLocation.getLatitude() == 0 && SettingsActivity.mUseUnicapLocation) {
                    mLocation = SettingsActivity.mUnicapLocation;
                }

                message += ":" + mLocation.getLatitude() + ";" + mLocation.getLongitude();

                createWaitDialog();
                mComunicationTask = new TaskComunication(mDialog, message);
                mComunicationTask.execute();
                setWaitDialogTimeout(10000, mDialog);
            }
        });

        ((Button) mDialogConfirmation.findViewById(R.id.buttonCancel)).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                mDialogConfirmation.dismiss();
            }
        });

        mDialogConfirmation.show();

    }

    private void createWaitDialog() {
        mDialog = new ProgressDialog(this);
        mDialog.setMessage("Aguarde...");
        mDialog.setCancelable(false);
        mDialog.setOnDismissListener(new OnDismissListener() {

            @Override
            public void onDismiss(DialogInterface dialog) {
                ProcessServerResponse();
            }
        });
    }

    public void setWaitDialogTimeout(long time, final Dialog d) {
        new Handler().postDelayed(new Runnable() {
            public void run() {
                mDialog.dismiss();
                mMessage = "null";
                mComunicationTask.cancel(true);
            }
        }, time);
    }

    public void ShowMaps(Coordenate origin, Coordenate destination) {

        Intent intentMap = new Intent(MainActivity.this, MapActivity.class);
        intentMap.putExtra(MapActivity.ORIGIN, mLocation);
        intentMap.putExtra(MapActivity.DESTINATION, destination);
        mContext.startActivity(intentMap);
    }

    private void getGPSCoordenates() {

        mLocation = new Coordenate();
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);

    }

    @Override
    public void onLocationChanged(Location location) {

        mLocation.setLatitude(location.getLatitude());
        mLocation.setLongitude(location.getLongitude());
    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    protected void onDestroy() {
        mSpeechHandle.onDestroy();
        super.onDestroy();
    }

}
